package com.tpp.scheduler.rabbit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tpp.comm.pojo.TpTask;
import com.tpp.comm.util.TpConst;
import com.tpp.scheduler.mapper.TaskMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class CreateOrderRabbit{

    @Resource
    private TaskMapper taskMapper;

    private RabbitTemplate rabbitTemplate;

    @Resource
    private void confirmCallback(RabbitTemplate rabbitTemplate){
        this.rabbitTemplate = rabbitTemplate;
        this.rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                String id = correlationData.getId();
                log.info("订单信息提交:{}:{}:{}",correlationData.getId(),b,s);
                if(b){
                    //信息发送成功
                    taskMapper.updateStatus(correlationData.getId(),1);
                }else{
                    //信息发送失败
                    taskMapper.updateErrorMsg(correlationData.getId(),s);
                }
            }
        });
    }

    /**
     * 定时任务，搜索本地消息表，发送到消息队列
     */
    @Scheduled(initialDelay = 3,fixedDelay = 30,timeUnit = TimeUnit.SECONDS)
    public void rabbitmqTask(){
        //查询状态为0的任务
        LambdaQueryWrapper<TpTask> taskWrapper = Wrappers.lambdaQuery();
        taskWrapper.eq(TpTask::getStatus,0);
        List<TpTask> tpTasks = taskMapper.selectList(taskWrapper);
        //向队列发送消息
        for (TpTask tpTask : tpTasks) {
            //防止并发问题，在task上加锁
            LambdaUpdateWrapper<TpTask> taskUpdateWrapper = Wrappers.lambdaUpdate();
            taskUpdateWrapper.eq(TpTask::getId,tpTask.getId());
            taskUpdateWrapper.eq(TpTask::getVersion,tpTask.getVersion());
            taskUpdateWrapper.set(TpTask::getVersion,tpTask.getVersion()+1);
            int update = taskMapper.update(tpTask, taskUpdateWrapper);
            if(update>0){
                //获得使用权
                //向rabbitmq发送消息，设置生存时间
                rabbitTemplate.convertAndSend(TpConst.Rabbit.ORDER_EXCHANGE,TpConst.Rabbit.ORDER_QUEUE, tpTask, new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        MessageProperties messageProperties = message.getMessageProperties();
                        messageProperties.setAppId(tpTask.getId());
                        LocalDateTime overtime = tpTask.getOvertime();
                        LocalDateTime now = LocalDateTime.now();
                        //获取过期时间秒
                        long second = overtime.toEpochSecond(ZoneOffset.of("+8"))-now.toEpochSecond(ZoneOffset.of("+8"));
                        second = second>1?second*1000:1;//获取毫秒
                        //设置过期时间
                        messageProperties.setExpiration(String.valueOf(second));
                        return message;
                    }
                },new CorrelationData(tpTask.getId()));
            }
        }

    }
}
